<script setup>
import { artAddChannelsService, artEditChannelsService } from '@/api/article'
import { ref } from 'vue'
const dialogVisible = ref(false)

// 表单数据绑定
const formModel = ref({
  cate_name: '',
  cate_alias: ''
})

// 获取表单元素
const formRef = ref()

// 配置表单规则
const rules = {
  cate_name: [
    { required: true, message: '不为空', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名必须是1-10位的非空字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是1-15位的字母数字',
      trigger: 'blur'
    }
  ]
}

// 只有添加时传入{}
const open = (row) => {
  dialogVisible.value = true
  console.log(row)
  // 编辑时额外传入id
  formModel.value = { ...row }
}

// 通知父组件刷新页面
const emit = defineEmits(['success'])

const onSubmit = async () => {
  await formRef.value.validate()
  const isEdit = formModel.value.id
  if (isEdit) {
    // 编辑
    await artEditChannelsService(formModel.value)
  } else {
    // 添加
    await artAddChannelsService(formModel.value)
  }
  ElMessage({
    type: 'success',
    message: isEdit ? '编辑成功' : '添加成功'
  })
  dialogVisible.value = false
  emit('success')
}


defineExpose({
  // 暴露组件数据
  open
})

</script>

<template>
  <el-dialog v-model="dialogVisible" :title="formModel.id ? '编辑分类' : '添加分类'" width="500">
    <!-- <span>This is a message</span> -->

    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="100px" style="padding-right: 30px">
      <el-form-item label="分类名称:" prop="cate_name">
        <el-input minlength="1" maxlength="10" v-model="formModel.cate_name" placeholder="请输入分类名称"></el-input>
      </el-form-item>
      <el-form-item label="分类别名:" prop="cate_alias">
        <el-input minlength="1" maxlength="15" v-model="formModel.cate_alias" placeholder="请输入分类别名"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="onSubmit">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>